package spark;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class JavaWordCount {
    public static void main(String[] args) {
        if(args.length!=2){
            System.out.println("Usage:cn.jixiang.spark.day01.ScalaWordCount <input><output>");
            System.exit(1);
        }

        SparkConf conf = new SparkConf();
        conf.setMaster("local");
        conf.setAppName(JavaWordCount.class.getSimpleName());
        //使用java程序来编写spark
        JavaSparkContext jsc = new JavaSparkContext(conf);
        //读文件
        JavaRDD<String> lines = jsc.textFile(args[0]);

        //切分并压平
        //flatMap方法中，参数的类型是一个接口两个参数，一个输入参数，一个输出参数
        JavaRDD<String> flatedData = lines.flatMap(new FlatMapFunction<String, String>() {
            public Iterator<String> call(String line) throws Exception {
                //该方法的返回值类型是迭代器
                return Arrays.asList(line.split(" ")).iterator();
            }
        });

        //和1组成元组
        //第一个参数数输入数据的类型，第二个参数是返回值类型（元组的Key）,第三个参数是返回值类型（元组的value）
        JavaPairRDD<String, Integer> wordAndOne = flatedData.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<String, Integer>(s, 1);
            }
        });

        //分组聚合
        //reduceByKey((a,b)=>a+b) 最后一个Integer表示返回值的类型
        JavaPairRDD<String, Integer> grouped = wordAndOne.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        //先在本地测试
        /*grouped.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> line) throws Exception {
                System.out.println(line);
            }
        });*/

        //排序前
        JavaPairRDD<Integer, String> beforeSort = grouped.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() {
            public Tuple2<Integer, String> call(Tuple2<String, Integer> tp) throws Exception {
                //把元组的KV互换
                return tp.swap();
            }
        });

        //排序
        JavaPairRDD<Integer, String> sortedData = beforeSort.sortByKey(false);

        //排序后
        JavaPairRDD<String, Integer> result = sortedData.mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(Tuple2<Integer, String> tp) throws Exception {
                return tp.swap();
            }
        });
        //把结果放到文件中
        result.saveAsTextFile(args[1]);
        //释放资源
        jsc.stop();
    }
}
